package com.xuzhiguang.lightnat.server.core.server.transfer.handler;

import com.xuzhiguang.lightnat.common.manager.ProxyChannelManager;
import com.xuzhiguang.lightnat.server.core.server.transfer.TransferChannelManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class WritabilityChangedHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {

        Long sessionId = TransferChannelManager.getSessionId(ctx.channel());
        if (sessionId == null) {
            log.warn("sessionId is null. channel:{}", ctx.channel());
        } else {
            Channel proxyChannel = ProxyChannelManager.get(sessionId);
            if (proxyChannel == null) {
                log.warn("proxyChannel is null. sessionId:{}", sessionId);
            } else {
                proxyChannel.config().setAutoRead(ctx.channel().isWritable());
            }
        }

        super.channelWritabilityChanged(ctx);
    }
}
